<!-- 我的领养页面-我购买的（我领养的宠物） -->
<template>
    <div class="order-box">
        <div class="order-table">
            <el-table :data="currentPageData" border style="width: 100%">
                <el-table-column prop="petName" label="宠物名字" />
                <el-table-column prop="deposit" label="押金" />
                <el-table-column prop="adopterAddress" label="领养人地址" />

                <!--  -->
                <el-table-column label="订单状态">
                    <template #default="{ row }">
                        <el-tag :type="getOrderStatusType(row.orderStatus)" :style="getTagStyle(row.orderStatus)" plain
                            disable-transitions>
                            {{ row.orderStatus }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="创建订单时间">
                    <template #default="{ row }">
                        {{ row.createTime ? row.createTime.replace('T', ' ') : "" }}
                    </template>
                </el-table-column>
                <el-table-column label="完成订单时间">
                    <template #default="{ row }">
                        {{ row.deliveryTime ? row.deliveryTime.replace('T', ' ') : "订单未完成" }}
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作" min-width="120px">
                    <template #default="scope">
                        <el-button type="primary" plain size="small" @click="Cancel(scope.row)">
                            取消订单
                        </el-button>
                        <el-button type="primary" plain size="small" @click="ConfirmGoods(scope.row)">
                            确认收货
                        </el-button>
                        <el-button type="primary" plain size="small" @click="Posequestion(scope.row)"
                            :disabled="scope.row.orderStatus !== '已发货'">
                            对该订单有疑问
                        </el-button>

                    </template>
                </el-table-column>

            </el-table>

            <!-- 分页器 -->
            <div class="pagination-container">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[8]" :page-size="pageSize" layout="prev, pager, next"
                    :total="total" />
            </div>
        </div>
    </div>


    <!-- 发起疑问表单 -->
    <el-dialog v-model="dialogFormVisible" title="请填写领养信息" width="500">

        <!-- 只读功能 -->
        <!-- 用户ID-发起疑问人的ID -->
        <!-- <el-form-item label="用户ID" :label-width="formLabelWidth">
            <el-input v-model="userId" disabled placeholder="系统自动填充" />
        </el-form-item> -->
        <el-form-item label="订单ID" :label-width="formLabelWidth">
            <el-input v-model="form.orderId" disabled placeholder="系统自动填充" />
        </el-form-item>


        <!-- 填写疑问表单信息 -->
        <el-form :model="form">
            <el-form-item label="发起疑问原因" :label-width="formLabelWidth">
                <el-input v-model="form.reason" autocomplete="off" />
            </el-form-item>

            <!-- 上传图片 -->
            <!-- <el-form-item label="上传证明图片" :label-width="formLabelWidth">
                <div class="upload-container">
                    <el-upload class="upload-demo" ref="uploadRef" action="#" drag :on-change="handlePictureChange"
                        :show-file-list="false" :auto-upload="false">
                        <div class="el-upload__text">
                            拖拽文件，或
                            <em>点击上传</em>
                        </div>
                        <div class="el-upload__tip" slot="tip">
                            请上传能证明您有能力领养宠物的图片
                        </div>
                    </el-upload>
                    <div v-if="previewUrl" class="preview-container">
                        <img :src="previewUrl" class="preview-image" alt="预览图" />
                        <el-button @click="removeImage" type="danger" size="small">删除图片</el-button>
                    </div>
                </div>
            </el-form-item> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false; resetUpload()">取消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false; confrimAsk()">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { getUserAdoptPetListAPI, postCancleOrderAPI, postConfirmGoodsAPI, postQuestionOrderAPI } from "@/api/user"
import { postImageAPI } from "@/api/pet"
import { useUserStore } from "@/stores/user"
import { ElMessage } from 'element-plus'
import { onMounted, ref, computed, reactive } from "vue"

const userStore = useUserStore()
const userId = userStore.user.user_id

console.log("用户ID:", userId)
// 获取并且存储
const OrderData = ref([])
const total = ref(0) // 总数据量
const currentPage = ref(1) // 当前页码
const pageSize = ref(8) // 每页显示数量

const getUserAdoptPetList = async () => {
    const res = await getUserAdoptPetListAPI(userId)
    OrderData.value = res.data.items
    total.value = res.data.items.length
    // console.log(OrderData.value)
}

onMounted(() => {
    getUserAdoptPetList()
})

//   取消订单-取消订单接口
const Cancel = async (row) => {
    console.log("取消订单ID", row.id)

    const res = await postCancleOrderAPI(row.id)
    console.log(res)
    if (res.message === "成功") {
        ElMessage.success("订单取消成功");
        getUserAdoptPetList()
    } else {
        ElMessage.error(res.message);
        getUserAdoptPetList()
    }
}

//   确认收货-订单完成接口
const ConfirmGoods = async (row) => {
    console.log("订单完成，确认收货ID：", row.id)

    const res = await postConfirmGoodsAPI(row.id)
    console.log(res)
    if (res.message === "成功") {
        ElMessage.success("订单已完成，押金已退还");
    } else {
        ElMessage.error(res.message);
    }
    getUserAdoptPetList()
}

//   对订单发起疑问按钮
const Posequestion = (row) => {
    console.log("对订单有疑问ID:", row.id)

    // 弹窗
    dialogFormVisible.value = true
    //赋值给orderId
    form.orderId = row.id
}

// 表单数据存储
const form = reactive({
    "orderId": 0, // 订单ID（添加双引号）
    "reason": "", // 发起疑问的原因（添加双引号）
    // "imageUrls": [] // 上传的图片（证明图片）
});

const formLabelWidth = '180px'//输入框标题宽度
const dialogFormVisible = ref(false)

// 上传图片相关
const uploadRef = ref(null)
const uploadFile = ref(null)// 存储上传的文件对象
const previewUrl = ref("")//存储上传图片的URL
// 处理图片上传
const handlePictureChange = async (file, fileList) => {
    const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
    const isLt50M = file.raw.size / 1024 / 1024 < 10

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!')
        return false
    }
    if (!isLt50M) {
        ElMessage.error('上传图片大小不能超过 10MB!')
        return false
    }

    try {
        // 创建FormData对象，用于上传文件
        const formData = new FormData()
        formData.append('file', file.raw)

        // 调用上传图片的接口
        const res = await postImageAPI(formData)
        console.log(res.url)

        // 处理接口返回的数据，将url存储在ruleForm.imageUrls数组中
        form.imageUrls.push(res.url)

        previewUrl.value = res.url
        uploadFile.value = file.raw
    } catch (error) {
        ElMessage.error('图片上传失败')
    }
}
// 删除预览图片
const removeImage = () => {
    uploadFile.value = null;
    previewUrl.value = '';
    // 从数组中移除对应的图片URL
    const index = form.images.indexOf(previewUrl.value)
    if (index > -1) {
        form.images.splice(index, 1)
    }
}

const resetUpload = () => {
    console.log("表单取消按钮")
}

// 发起疑问表单确认按钮-调用发起疑问接口
const confrimAsk = async () => {
    console.log("发起疑问表单确认按钮")
    // console.log("发起疑问表单信息：",form)
    console.log("请求体JSON：", JSON.stringify(form));
    // 调用发起疑问接口
    const res = await postQuestionOrderAPI(userId, form)
    console.log(res)
    ElMessage(res.message)
}



// 定义颜色状态  
const getOrderStatusType = (status) => {
    switch (status) {
        case '申请中':
            return 'primary'
        case '已取消':
            return 'info'
        case '申请失败':
            return 'danger'
        case '未发货':
            return 'warning'
        case '已发货':
            return 'default' // 类型保持默认  
        case '已完成':
            return 'success'
        default:
            return 'default'
    }
}
const getTagStyle = (status) => {
    if (status === '已发货') {
        return { backgroundColor: '#bbe4de', color: '#fff' }
    }
    return {} // 其他状态无特殊样式  
}

// 计算当前页数据
const currentPageData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return OrderData.value.slice(start, start + pageSize.value)
})

// 分页器事件处理
const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1 // 切换每页数量后回到第一页
    getUserAdoptPetList() // 重新获取数据
}

const handleCurrentChange = (newPage) => {
    currentPage.value = newPage
}
</script>

<style lang="scss" scoped>
.order-box {
    width: 970px;
    margin-left: 30px;
    // border: 1px solid black;
    padding: 15px;
    position: relative;
    background: #FAFAFA;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
    padding: 10px;
    position: absolute;
}

.upload-container {
    .preview-container {
        margin-top: 10px;
    }

    .preview-image {
        max-width: 100%;
        max-height: 100px;
        border-radius: 4px;
        border: 1px solid #ebeef5;
    }
}
</style>